﻿using CsvHelper;
using FireBillBook.Core.Entities;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using FireBillBook.Core.Models.OriginalDatas;
using System.Linq;
using System.IO;
using FireBillBook.Core.Models;
using AutoMapper;
using Microsoft.Extensions.DependencyInjection;

namespace FireBillBook.Core.Services
{
    public class WechatPayService : BasePlatformService
    {
        

        public override Stream CleanData(Stream rawStream, Encoding defaultEncoding)
        {
            if(defaultEncoding == null)
            {
                defaultEncoding = Encoding.Default;
            }

            int lineIndex = 0;  // 行号
            string line;        // 行
            var cleanedLines = new List<string>();
            using var reader = new StreamReader(rawStream, defaultEncoding);

            while ((line = reader.ReadLine()) != null)
            {
                lineIndex += 1;

                if (lineIndex == 17)
                {
                    cleanedLines.Add(string.Join(",", line.Split(",").Select(a => a.Trim())));
                }

                // 正文数据
                if (lineIndex > 17)
                {
                    cleanedLines.Add(line.Replace("¥", ""));
                }
            }

            var memoryStream = new MemoryStream();
            using (var writer = new StreamWriter(memoryStream, Encoding.UTF8, leaveOpen: true))
            {
                foreach (var item in cleanedLines)
                {
                    writer.WriteLine(item);
                }

                writer.Flush();
                memoryStream.Position = 0;
            }
            // 回到开头位置
            return memoryStream;
        }

        public override async Task<List<BillingSourceData>> ConvertOriginalDatas(CsvReader reader)
        {
            reader.Context.RegisterClassMap<Models.ImportMaps.WechatPaymentRecordMap>();

            var datas = await reader.GetRecordsAsync<WechatPaymentOriginalData>().ToListAsync();

            var records = Mapper.Map<List<BillingSourceData>>(datas);

            return records;
        }
    }
}
